var log4js = require('log4js');
var http = require('http');

var authPwd = 'socket.io.password';
var resCache = {};
var pvCount = 0;

log4js.configure({
  appenders: [
    {
      type: 'dateFile',
      filename: 'logs/',
      pattern: 'log_yyyy-MM-dd.log',
      alwaysIncludePattern: true,
      category: 'proxy'
    },
    {
      type: 'console',
      category: 'proxy'
    }
  ],
  levels: {
    rpi: 'DEBUG'
  }
});

var logger = log4js.getLogger('proxy');
var lanSocket = null;
var server = http.createServer(app);
var io = require('socket.io')(server);
server.listen(80);

server.on('error', function (err) {
  logger.error(err);
  logger.info('Server Start Failed. Plz check if 80 PORT in use');
});

io.on('connection', function(socket) {
  logger.log('WebSocket Connected.');

  socket.on('auth', function(data) {
    if(data === authPwd) {
      lanSocket = socket;
      socket.emit('success',true);

      lanSocket.on('response', function (data) {
        if(data.id && data.id in resCache) {
          data.headers && resCache[data.id].writeHead(data.status, data.headers);
          var buffer = new Buffer(data.body,'hex');
          resCache[data.id].end(buffer);
          resCache[data.id] = null;
          return;
        }
        logger.error('ERROR Response OR ResCache Missed.');
      });

    } else {
      socket.emit('success',false);
    }
  });
});

function app (req, res) {
  if(lanSocket === null) {
    logger.error("Lan Server Not Exist.");
    res.end('LocalServer ERROR');
  } else {
    pvCount++;
    logger.info('Proxy Count : ' + pvCount);
    resCache[pvCount] = res;

    var serializedReq = {
      id: pvCount,
      headers: req.headers,
      method: req.method,
      url: req.url
    };
    lanSocket.emit('request', serializedReq);

    req.on('data', function (chunk) {
      lanSocket.emit('data', {
        id: pvCount,
        data: chunk
      });
    });

    req.on('end', function () {
      lanSocket.emit('end', pvCount);
    });
    logger.info("Pipe Request to Local");
  }
}

logger.info('Proxy Server Start...');